package com.wfh.mianshi.blackfilter;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.util.List;
import java.util.Map;

/**
 * @Author FengHuan Wang
 * @Date 2025/4/25 10:03
 * @Version 1.0
 */
@Slf4j
public class BlackIpUtils {

    public static BitMapBloomFilter bitMapBloomFilter;

    /**
     * 判断ip是否在黑名单里面
     * @param ip
     * @return
     */
    public static boolean isBlackIp(String ip){
        return bitMapBloomFilter.contains(ip);
    }

    /**
     * 重建ip黑名单
     * @param configInfo
     */
    public static void rebuildBlackIp(String configInfo){
        if (StrUtil.isBlank(configInfo)){
            configInfo = "{}";
        }
        // 解析yaml文件
        Yaml yaml = new Yaml();
        Map<String, List<String>> map = yaml.loadAs(configInfo, Map.class);
        // 获取ip黑名单
        List<String> blackIpList = (List<String>) map.get("blackIpList");
        // 防止并发安全问题
        synchronized (BlackIpUtils.class){
            if (CollUtil.isNotEmpty(blackIpList)){
                // 注意构造参数的设置
                BitMapBloomFilter bloomFilter = new BitMapBloomFilter(100);
                for (String ip : blackIpList) {
                    bloomFilter.add(ip);
                }
                bitMapBloomFilter = bloomFilter;
            }else {
                bitMapBloomFilter = new BitMapBloomFilter(100);
            }
        }

    }

}
